import json
import time

import pandas as pd

import BiAn
import util


def get_close_position_percentage(df):
    """
    计算最后一个close价格在历史区间中的百分比位置

    参数:
        df (pd.DataFrame): 包含币安K线数据的DataFrame，需有'close'列

    返回:
        float: 最后一个close在区间中的百分比位置(0-100)
        tuple: (区间最小值, 区间最大值, 最后一个close值)
    """
    if df.empty or 'close' not in df.columns:
        return None, (None, None, None)

    # 确保close是数值类型
    close_prices = pd.to_numeric(df['close'], errors='coerce').dropna()

    if len(close_prices) < 1:
        return None, (None, None, None)

    # 计算区间
    min_close = close_prices.min()
    max_close = close_prices.max()
    last_close = close_prices.iloc[-1]

    # 计算百分比位置
    if max_close == min_close:  # 避免除以0
        position_pct = 50.0  # 如果区间没有波动，默认中间位置
    else:
        position_pct = ((last_close - min_close) / (max_close - min_close)) * 100

    return position_pct, (min_close, max_close, last_close)

def c(item):
    try:
        df = BiAn.get_binance_data(limit_var=150, symbol=item['symbol'] + 'USDT', interval="15m")
        # 计算位置百分比
        pct_position, (min_val, max_val, last_close) = get_close_position_percentage(df)

        if pct_position is not None:
            if pct_position > 50:
                item['key'] = True
            else:
                item['key'] = False
            if pct_position > 75:
                print("========================================================")
                print(f"最近200根15分钟K线的收盘价区间: {min_val:.6f} - {max_val:.6f}")
                print(f"最新收盘价: {last_close:.6f}")
                print(f"{item['symbol']}当前位置百分比: {pct_position:.6f}%")
                print(f"{item['symbol']}价格处于区间高位(>75%) 市值：{round(float(item['shizhi'])/100000000,2)}亿")
                df = BiAn.get_binance_data(limit_var=200, symbol=item['symbol'] + 'USDT', interval="5m")
                pct_position, (min_val, max_val, last_close) = get_close_position_percentage(df)
                util.play_voidce("有币种达到卖出区域")
                if pct_position > 90:
                    util.play_voidce("5分钟卖出区域")
                    print(f"5分钟卖出区域：{pct_position:.6f}%")
                print("========================================================")
            elif pct_position < 30:
                print(f"{item['symbol']}价格处于区间低位(<30%)，" + f"当前位置百分比: {pct_position:.6f}%")
            else:
                print(f"{item['symbol']}价格处于区间中部，市值：{round(float(item['shizhi'])/100000000,2)}亿，" + f"当前位置百分比: {pct_position:.6f}%")
    except Exception as e:
        print(f"处理 {item['symbol']} 时出错: {e}")

def monitor_all():
    data = []
    data_min = []
    data_user = []
    filter = ['USDC']
    with open('select_usdt.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
    with open('select_usdt_min.json', 'r', encoding='utf-8') as file:
        data_min = json.load(file)
    with open('select_usdt_user.json', 'r', encoding='utf-8') as file:
        data_user = json.load(file)
    while True:
        for item in data:
            # print(item)
            if item['symbol'] in filter:
                continue
            if "key" in item and item['key'] == False:
                item['key'] = True
                continue
            c(item)
            time.sleep(5)
        print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
        for item in data_min:
            # print(item)
            if item['symbol'] in filter:
                continue
            c(item)
            time.sleep(5)
        print("-----------------------------------------------------------------------------------------")
        for item in data_user:
            # print(item)
            if item['symbol'] in filter:
                continue
            c(item)
            time.sleep(5)
        print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||")
        time.sleep(2 * 60)


def monitor_symbols():
    filter = ['BTSUSDT',"ETHUSDT"]
    with open('symbol_list_BIG.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
    with open('symbol_list_NORMAL_BIG.json', 'r', encoding='utf-8') as file:
        data_min = json.load(file)
    with open('symbol_list_NORMAL.json', 'r', encoding='utf-8') as file:
        data_user = json.load(file)
    while True:
        for item in data['symbols']:
            if item in filter:
                continue
            c({"shizhi":4*100000000,"symbol":item})
            time.sleep(5)
        print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
        for item in data_min:
            if item in filter:
                continue
            c({"shizhi": 3 * 100000000, "symbol": item})
            time.sleep(5)
        print("-----------------------------------------------------------------------------------------")
        for item in data_user:
            if item in filter:
                continue
            c({"shizhi": 2 * 100000000, "symbol": item})
            time.sleep(5)
        print("||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||")
        time.sleep(2 * 60)

monitor_symbols()